package com.yzy.baselibrary.utils

import android.os.Build
import android.os.Environment.getRootDirectory
import android.text.TextUtils
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.lang.reflect.InvocationTargetException
import java.util.*


/**
 *description: 系统工具类.
 *@date 2018/12/21 17:52.
 *@author: YinZeYu.
 */
object SystemUtil {
  private val KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code" //小米
  private val KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name"
  private val KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage"

  /**
   * 小米系统
   *
   * @return
   */
  fun isMIUI(): Boolean {
    var isMIUI = false
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
      try {
        if (!TextUtils.isEmpty(getSystemProperty(KEY_MIUI_VERSION_CODE, ""))
            || !TextUtils.isEmpty(getSystemProperty(KEY_MIUI_VERSION_NAME, ""))
            || !TextUtils.isEmpty(getSystemProperty(KEY_MIUI_INTERNAL_STORAGE, ""))) {
          isMIUI = true
        }
      } catch (e: Exception) {
        e.printStackTrace()
      }

    } else {
      val prop = Properties()
      try {
        prop.load(FileInputStream(File(getRootDirectory(), "build.prop")))
      } catch (e: IOException) {
        e.printStackTrace()
        return false
      }

      isMIUI = (prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
          || prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
          || prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null)
    }
    return isMIUI
  }

  private fun getSystemProperty(key: String, defaultValue: String): String {
    try {
      val clz = Class.forName("android.os.SystemProperties")
      val get = clz.getMethod("get", String::class.java, String::class.java)
      return get.invoke(clz, key, defaultValue) as String
    } catch (e: ClassNotFoundException) {
    } catch (e: NoSuchMethodException) {
    } catch (e: IllegalAccessException) {
    } catch (e: IllegalArgumentException) {
    } catch (e: InvocationTargetException) {
    }

    return defaultValue
  }

}